import React, { useState, useEffect, useMemo, useContext } from 'react';
import {
  Table,
  Card,
  Button,
  Space,
  Popover,
  Checkbox,
  Message,
  Modal,
  Typography,
  Dropdown,
  Menu,
  PaginationProps,
} from '@arco-design/web-react';
import {
  IconDownload,
  IconFilter,
  IconHistory,
  IconPlus,
} from '@arco-design/web-react/icon';
import cs from 'classnames';
import useLocale from '@/utils/useLocale';
import SearchForm from './form';
import locale from './locale';
import styles from './style/index.module.less';
import { getColumns } from './constants';
import { GlobalContext } from '@/context';
import { Active, Export, Resend, Search } from '@/api/modules/entityProfiles';
import Create from './create';
import { useDownload } from '@/utils/useDownload';
import ActionWrapper from '@/components/ActionWrapper';
import { entityProfilesCreate } from '@/api/interface/entityProfiles';
import useIsMountedRef from '@/utils/useIsMountedRef';
import useStorageJson from '@/utils/useStorageJson';
import LoginHistory from './LoginHistory';
import { useSelector } from 'react-redux';
import { GlobalState } from '@/store';
import isEmpty from 'lodash/isEmpty';
import has from 'lodash/has';
import debounce from 'lodash/debounce';

const { Title } = Typography;

function EntityProfiles() {
  const t = useLocale(locale);
  const { rtl, lang } = useContext(GlobalContext);

  const [record, setRecord] = useState<entityProfilesCreate>({
    id: '',
    active: false,
    admin: false,
    email: '',
    emirate: null,
    entityId: null,
    jobDescription: '',
    mobile: '',
    officerName: '',
    officerNameAr: '',
  });
  const tableCallback = async (record: entityProfilesCreate, type: string) => {
    if (type === 'resendTheLink') {
      Resend(record.id).then(() => {
        Message.success(t['searchTable.operation.resendTheLink.success']);
      });
      return;
    }
    if (type === 'edit') {
      setRecord(record);
      onVisible(true);
      return;
    }
    if (type === 'editActive') {
      setMldalStatus(true);
      setRecord(record);
      return;
    }
    return;
  };
  const { userInfo } = useSelector((state: GlobalState) => state);
  const [tableColumns, setTableColumns] = useStorageJson(
    `${userInfo.id}_entityProfiles_tableColumns`,
    [
      'id',
      'entity',
      'officerName',
      'officerNameAr',
      'admin',
      'mobile',
      'email',
      'active',
      'action',
      'officerNumber',
    ]
  );
  const options = [
    {
      label: t['searchTable.columns.number'],
      value: 'id',
      width: 60,
    },
    {
      label: t['searchTable.columns.name'],
      value: 'entity',
      width: 140,
    },
    {
      label: t['searchTable.columns.officerNameEn'],
      value: 'officerName',
      width: 180,
    },
    {
      label: t['searchTable.columns.officerNameAr'],
      value: 'officerNameAr',
      width: 180,
    },
    {
      label: t['searchTable.columns.admin'],
      value: 'admin',
      width: 140,
    },

    {
      label: t['searchTable.columns.active'],
      value: 'active',
      width: 140,
    },
    {
      label: t['searchTable.columns.mobile'],
      value: 'mobile',
      width: 140,
    },
    {
      label: t['searchTable.columns.email'],
      value: 'email',
      width: 220,
    },
    {
      label: t['searchTable.columns.officerNumber'],
      value: 'officerNumber',
      width: 140,
    },

    {
      label: t['searchTable.columns.action'],
      value: 'action',
      width: 140,
    },
  ];

  const columns = useMemo(
    () => getColumns(t, tableCallback, tableColumns, options, lang),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [t, tableColumns]
  );

  const width = useMemo(
    () => {
      return columns.reduce((sum, { width = 0 }) => sum + width, 0) || 140;
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [columns]
  );

  const [visible, setVisible] = useState(false);
  const onVisible = (status: boolean, refresh?: boolean) => {
    setVisible(status);
    if (refresh) {
      if (pagination.current === 1) {
        fetchData();
        return;
      }
      setPatination({ ...pagination, current: 1 });
    }
  };

  const [data, setData] = useState([]);
  const [pagination, setPatination] = useState<PaginationProps>({
    sizeOptions: [10, 20, 50, 100],
    sizeCanChange: true,
    showTotal: true,
    pageSize: 10,
    current: 1,
    pageSizeChangeResetCurrent: true,
  });
  const [loading, setLoading] = useState(true);
  const [formParams, setFormParams] = useState<any>();
  const isMountedRef = useIsMountedRef();
  useEffect(() => {
    if (!formParams) {
      return;
    }
    console.log(formParams);
    fetchData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagination.current, pagination.pageSize, JSON.stringify(formParams)]);

  async function fetchData() {
    const { current, pageSize } = pagination;
    setLoading(true);
    try {
      const { data } = await Search({
        pageNo: current,
        pageSize,
        ...formParams,
      });
      if (isMountedRef.current) {
        setData(data.data);
        setPatination({
          ...pagination,
          current,
          pageSize,
          total: data.count,
        });
        setLoading(false);
      }
    } catch {
      setLoading(false);
    }
  }

  function onChangeTable({ current, pageSize }) {
    setPatination({
      ...pagination,
      current,
      pageSize,
    });
  }

  const handleSearch = debounce((params) => {
    if (has(params, 'active')) {
      params.active =
        params.active === 1 ? true : params.active === 0 ? false : '';
    }
    if (has(params, 'admin')) {
      params.admin =
        params.admin === 1 ? true : params.admin === 0 ? false : '';
    }
    setPatination({ ...pagination, current: 1 });
    setFormParams(params);
  }, 300);

  const CheckboxGroup = Checkbox.Group;

  const tableColumnsFilter = () => (
    <CheckboxGroup
      direction="vertical"
      key={lang}
      options={options.map((a) => {
        let disabled = false;
        if (tableColumns.length === 1) {
          disabled = tableColumns.includes(a.value);
        }

        return { ...a, disabled };
      })}
      value={tableColumns}
      onChange={(value) => {
        if (value.length < 1) {
          return;
        }
        setTableColumns(value);
      }}
    />
  );

  async function ExportExcel(e) {
    const params = {
      ...formParams,
      fields: tableColumns,
    };
    await useDownload(
      Export,
      lang === 'ar-EG' ? 'مشرف الجهة' : 'Supervisor',
      lang === 'ar-EG' ? 'ar' : 'en',
      e,
      e === 1 ? '.csv' : '.xlsx',
      params
    );
  }

  const [modalStatus, setMldalStatus] = useState<boolean>(false);
  const [modalLoading, setModalLoading] = useState<boolean>(false);

  const [history, setHistory] = useState<boolean>(false);

  return (
    <Card>
      <div className={styles['page-header']}>
        <Title heading={6} className={styles['page-title']}>
          {/* {t['searchTable.form.title']} */}
        </Title>
        <IconHistory
          className={styles['page-header-icon']}
          onClick={() => setHistory(true)}
        />
      </div>

      <SearchForm onSearch={handleSearch} formParams={formParams} />
      <Create visible={visible} onVisible={onVisible} record={record} />

      <div className={cs(styles['button-group'], rtl ? 'rtl' : '')}>
        <Space>
          <ActionWrapper action="complaintofficer.compliance/create">
            <Button
              type="primary"
              icon={<IconPlus />}
              onClick={() => {
                setRecord({
                  id: '',
                  active: false,
                  admin: false,
                  email: '',
                  emirate: '',
                  entityId: null,
                  jobDescription: '',
                  mobile: '',
                  officerName: '',
                  officerNameAr: '',
                }),
                  onVisible(true);
              }}
            >
              {t['searchTable.operations.add']}
            </Button>
          </ActionWrapper>
        </Space>
        <Space>
          <Popover
            position="bottom"
            trigger="click"
            content={tableColumnsFilter}
          >
            <Button icon={<IconFilter />}>
              {t['searchTable.operation.filter']}
            </Button>
          </Popover>
          <Dropdown
            droplist={
              <Menu>
                <Menu.Item
                  key="1"
                  className={styles['export-text']}
                  onClick={() => ExportExcel(1)}
                >
                  CSV
                </Menu.Item>
                <Menu.Item
                  key="2"
                  className={styles['export-text']}
                  onClick={() => ExportExcel(2)}
                >
                  Excel
                </Menu.Item>
              </Menu>
            }
            position="bottom"
          >
            <Button type="primary" icon={<IconDownload />}>
              {t['searchTable.operation.export']}
            </Button>
          </Dropdown>
        </Space>
      </div>
      <Table
        border={{
          wrapper: true,
          cell: true,
        }}
        rowKey="id"
        loading={loading}
        onChange={onChangeTable}
        pagination={pagination}
        columns={columns}
        data={data}
        scroll={{
          x: width,
        }}
      />

      <Modal
        confirmLoading={modalLoading}
        closable
        style={{ width: '760px' }}
        title={
          <>
            {record.active
              ? t['modal.deactivate.title']
              : t['modal.activate.title']}
            <span style={{ fontWeight: 'bold', color: '#ff4000' }}>
              {'  '}
              {record.officerName}({record.officerNameAr})
            </span>
            {lang == 'en-US' ? '?' : '؟'}
          </>
        }
        className={cs(rtl ? 'rtl' : '')}
        visible={modalStatus}
        simple
        okText={record.active ? t['modal.deactivate'] : t['modal.activate']}
        onOk={() => {
          setModalLoading(true);
          Active({ id: record.id, active: record.active ? false : true })
            .then(() => {
              Message.success(
                record.active
                  ? t['modal.deactivate.success']
                  : t['modal.activate.success']
              );
              setMldalStatus(false);
              setModalLoading(false);
              fetchData();
            })
            .catch(() => {
              setModalLoading(false);
            });
        }}
        onCancel={() => {
          setMldalStatus(false);
        }}
      ></Modal>

      <LoginHistory visible={history} setVisible={setHistory}></LoginHistory>
    </Card>
  );
}

export default EntityProfiles;
